package com.rdk.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import com.rdk.constant.StrConstant;
import com.rdk.entity.TUser;
import com.rdk.entity.TUserRelation;
import com.rdk.service.TUserRelationService;
import com.rdk.service.TUserService;
import com.rdk.service.impl.TUserRelationServiceImpl;
import com.rdk.service.impl.TUserServiceImpl;
import com.rdk.utils.CommonUtil;
import com.rdk.utils.StringUtil;
import com.rdk.utils.WechatInterfacesUtils;
import com.rdk.wechat.util.JSONutils;

/**
 * 过滤器
 * @author wang_lei
 *
 */
public class UserFilter implements Filter {

	protected final static Log logger = LogFactory.getLog(UserFilter.class);	
	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse)res;
	
		/*String isRerequest = request.getParameter("isRerequest");
		//isRerequest：1    重新通过clientKey请求用户接口
		if(StringUtils.equals(isRerequest, "1")){
			String clientKey = request.getParameter("clientKey");
		}*/
		
		
		/** 
		 * 1.从reuqest中获取clienKey,如果该值不为空，则调用接口方法
		 * 获取usesToken,accessToken,向本地数据库同步用户信息和用户
		 * 好友列表。
		 */
		
		//国际化
		getMessagesLangType(request, CommonUtil.getRequest(request, "lang"));
		
		String clientKey = request.getParameter(StrConstant.PARAM_CLIENTKEY);
		System.out.println("clienKey: " + clientKey);
		this.haldUser(clientKey, request);
		
		/** 
		 * 2.判断session是否已经失效，
		 * 如果已经失效，则通过userToken重新获取用户信息，
		 * 考虑到系统新能上的问题，此处不做用户信息同步
		 * */
		//String userToken1 = CommonUtil.getRequest(request, StrConstant.PARAM_USERTONKEN);
		
		TUser userInfo = (TUser)CommonUtil.getSessionObj(request, StrConstant.PARAM_USERINFO);
		if (null == userInfo){
			String userToken = request.getParameter("userToken");
			String accessToken = WechatInterfacesUtils.getAccessToken();
			this.getUserInfo(userToken, request, accessToken);
			
		}
		
		
		chain.doFilter(request, response);
		return;
	}
	
	/**
	 * 国际化
	 * @param request
	 * @param langType
	 */
	private void getMessagesLangType(HttpServletRequest request,String langType){
		
		if("0".equals(langType)){
			langType = CommonUtil.getSession(request, "lang");
			if("0".equals(langType)){
				langType = "zh";
			}
		}
		CommonUtil.setSession(request, "lang", langType);
		if(langType.equals("zh")){
			Locale locale = new Locale("zh", "CN"); 
			request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale); 
		}
		else if(langType.equals("en")){
			Locale locale = new Locale("en", "US"); 
			request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale);
		}
		else {
			Locale locale = new Locale("zh", "CN"); 
			request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale); 
		}
		
	}
	
	/** 处理用户信息*/
	private void haldUser(String clientKey,HttpServletRequest request ){
		if (StringUtil.isNotEmpty(clientKey)){
			// 获取本地用户信息
			//1. 获取accessTonken
			String accessToken = WechatInterfacesUtils.getAccessToken();
			// 2.获取userToken
			String userToken = WechatInterfacesUtils.getUserToken(clientKey, accessToken);
			
			if (StringUtil.isNotEmpty(userToken)){
				// 3.获取用户信息
				TUser userInfo = this.getUserInfo(userToken, request, accessToken);
				// 5.处理好友信息
				this.haldUserBuddys(userToken, accessToken, userInfo, request);
				
			}
		}
	} 
	
	/**
	 * 获取用户信息
	 * 
	 * @param userToken
	 * @param request
	 * @param accessToken
	 */
	private TUser getUserInfo(String userToken, HttpServletRequest request, String accessToken){
		TUser user = null;
		if (StringUtil.isNotEmpty(userToken)){
			CommonUtil.setSession(request, StrConstant.PARAM_USERTONKEN, userToken);
			user = WechatInterfacesUtils.getUserInfo(userToken, accessToken);
			if (user != null){
				CommonUtil.setSession(request, StrConstant.PARAM_USERINFO, user);
				CommonUtil.setSession(request, StrConstant.PARAM_USERID, user.getUserId());
			}
		}
		return user;
	}
	
	/**
	 * 批量保存用户信息
	 * @param buddyList 用户好友信息列表
	 * @param userService
	 */
	private void saveUserInfo(List<TUserRelation> buddyList, TUserService userService){
		List<TUser> userList = new ArrayList<TUser>();
		
		for(TUserRelation buddy: buddyList){
			userList.add(buddy.getUser());
		}
		if (userList.size() > 0){
			userService.saveUserList(userList);
		}
	}
	
	/**
	 * 处理用户好友信息
	 * @param userToken
	 * @param accessToken
	 */
	private void haldUserBuddys(String userToken, String accessToken, TUser userInfo, HttpServletRequest request ){
		
		// 获取好友时间戳
		List<Integer> userBuddysTimestamp = WechatInterfacesUtils.getUserBuddysTimestamp(userToken, accessToken);
		
		// 获取本地用户信息
		ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
		TUserService userService = ctx.getBean(TUserServiceImpl.class);
		TUserRelationService userRelationService = ctx.getBean(TUserRelationServiceImpl.class);
		
		TUser userTemp = userService.findUserById(userInfo.getUserId());
	 
		String userTimesTampTemp = "[]";
		if (userTemp != null ){
			// StringUtil.isNotEmpty(userTemp.getTimestamp())
			userTimesTampTemp = userTemp.getTimestamp();
		}
		List<Object> timestampList = JSONutils.json2List(userTimesTampTemp);
		
		for (int i = 0; i < userBuddysTimestamp.size(); i++){
			Integer time = userBuddysTimestamp.get(i);
			
			if (i >= timestampList.size() || time > (Integer)timestampList.get(i)){
				// 清除对应的好友关系数据
				if (null != userTemp){
					Map<String, Object> paramMap = new HashMap<String, Object>();
					paramMap.put("userId", userTemp.getUserId());
					paramMap.put("page", i+1);
					userRelationService.deleteByIdAndPageNo(paramMap);
				}
				// 获取好友数据
				List<TUserRelation> buddyList = WechatInterfacesUtils.getUserRelation(userToken, accessToken, String.valueOf(i + 1), userInfo.getUserId());
				// 保存好友信息
				this.saveUserInfo(buddyList, userService);
				// 保存好友关系信息
			
				if (buddyList.size()>0){
					
					userRelationService.insertBatch(buddyList);
				}
				
			}
		}
		
		userInfo.setTimestamp(userBuddysTimestamp.toString());
		if (userTemp != null){
			userService.updateByPrimaryKeySelective(userInfo);
		}else{
			userService.insert(userInfo);
		}
	}
	

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}

}
